package com.bd.scm.module.qywx.init;


import com.bd.scm.domain.models.qywx.TToken;
import com.bd.scm.module.qywx.service.Listener;
import com.bd.scm.module.qywx.service.TTokenService;
import com.bd.scm.module.qywx.service.WxListener;
import com.bd.scm.module.qywx.thread.TokenThread;
import com.bd.scm.module.qywx.thread.WxTokenThread;
import com.bd.scm.module.utils.qywx.WeiXinParamesUtil;
import com.bd.scm.module.utils.wx.WXAuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;

/**
 * 初始化servlet
 *
 * @author YH
 */
@Component
public class InitServlet implements ApplicationRunner {

    @Value("${bd.thread.enable}")
    private boolean flag;

    private static Logger log = LoggerFactory.getLogger(InitServlet.class);

    @Autowired
    protected TTokenService tokenService;

    //企业微信获取凭证
    private TokenThread tokenThread;

    private static InitServlet initServlet;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
    	initServlet = this;
    	initServlet.tokenService = this.tokenService;
       // 初使化时将已静态化的testService实例化
    }

    //添加凭证
    public void saveToken(TToken token){
    	initServlet.tokenService.insert(token);
    }

    /**
     * 根据凭证获取创建时间
     * @param accessToken
     * @return
     */
    public String findTtokenTime(String accessToken) {
		return initServlet.tokenService.findTtokenTime(accessToken);
    }

	@Override
	public void run(ApplicationArguments args) throws Exception {
		// TODO Auto-generated method stub
//		initAccessToken();
	}

	//企业微信获取凭证
	public void initAccessToken() throws ServletException {
        // 获取web.xml中配置的参数
        TokenThread.corpId = WeiXinParamesUtil.getProperty("corpId");
        TokenThread.agentSecret = WeiXinParamesUtil.getProperty("agentSecret");

        log.info("weixin api appid:{}", TokenThread.corpId);
        log.info("weixin api appsecret:{}", TokenThread.agentSecret);

        // 未配置appid、appsecret时给出提示
        if ("".equals(TokenThread.corpId) || "".equals(TokenThread.agentSecret) || null == TokenThread.corpId ||null == TokenThread.agentSecret) {
            log.info("appid and appsecret configuration error, please check carefully.");
        } else {
            // 启动定时获取access_token的线程
            tokenThread = new TokenThread();
            Listener listen = new Listener();
            tokenThread.addObserver(listen);
            if(flag){
                new Thread(tokenThread).start();
            }
        }
    }

}
